package hhtc.jsjds.securityhandler;

import com.alibaba.fastjson.JSON;
import hhtc.jsjds.entity.UserInfo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Instant;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;



/**
 *
 * @author
 *@Description:用于处理一个成功的身份验证实现执行是处理导航到后续的目标.
 */
public class GoAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

//    @Autowired
//    JwtUtils jwtUtils;

    @CrossOrigin
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        UserInfo user = (UserInfo) authentication.getPrincipal();
        String jwtToken = null;
        try {
           jwtToken = this.generateToken(user.getId(),user.getUsername(),user.getAuthorities(),2*24*60*60);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map restResult = new HashMap();
        restResult.put("token", jwtToken);
        restResult.put("flag",true);
        httpServletResponse.getWriter().write(JSON.toJSONString(restResult));
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();;
    }

    public  String generateToken(String id, String username, Collection<? extends GrantedAuthority> authorities, int expireMinutes) throws Exception {
        Instant now = Instant.now();
        String token = Jwts.builder()
                .setSubject(username)
                .claim("authorities", authorities.stream()
                        .map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
                .claim("id",id)
                .setIssuedAt(Date.from(now))
                .setExpiration(Date.from(now.plusSeconds(expireMinutes)))
                .signWith(SignatureAlgorithm.HS256, "otherpeopledontknowit".getBytes())
                .compact();
//        redisTemplate.opsForValue().append(token,username);
        return token;
    }

}
